import { defineStore } from 'pinia';
import { Task, TaskComment, TaskQueryParams } from '../../models/task';
import * as taskApi from '../../api/taskApi';

export const taskStore = defineStore('task', {
  state: () => ({
    taskList: [] as Task[],
    currentTask: null as Task | null,
    taskComments: [] as TaskComment[],
    loading: false,
    total: 0,
    currentPage: 1,
    pageSize: 10,
    currentTeamId: 0,
  }),

  actions: {
    // 设置当前队伍ID
    setCurrentTeamId(teamId: number) {
      this.currentTeamId = teamId;
    },

    // 重置任务列表
    resetTaskList() {
      this.taskList = [];
      this.total = 0;
      this.currentPage = 1;
    },

    // 获取任务列表
    async fetchTaskList(params: TaskQueryParams) {
      this.loading = true;
      try {
        const res = await taskApi.getTaskList({
          ...params,
          page: params.page || this.currentPage,
          pageSize: params.pageSize || this.pageSize,
        });
        if (res.code === 200) {
          this.taskList = res.data.list || [];
          this.total = res.data.total || 0;
          this.currentPage = params.page || 1;
        }
        return res;
      } catch (error) {
        console.error('获取任务列表失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取我的任务
    async fetchMyTasks(params: TaskQueryParams) {
      this.loading = true;
      try {
        const res = await taskApi.getMyTasks({
          ...params,
          page: params.page || this.currentPage,
          pageSize: params.pageSize || this.pageSize,
        });
        if (res.code === 200) {
          this.taskList = res.data.list || [];
          this.total = res.data.total || 0;
          this.currentPage = params.page || 1;
        }
        return res;
      } catch (error) {
        console.error('获取我的任务失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取队伍任务
    async fetchTeamTasks(teamId: number, params: TaskQueryParams) {
      this.loading = true;
      try {
        const res = await taskApi.getTeamTasks(teamId, {
          ...params,
          page: params.page || this.currentPage,
          pageSize: params.pageSize || this.pageSize,
        });
        if (res.code === 200) {
          this.taskList = res.data.list || [];
          this.total = res.data.total || 0;
          this.currentPage = params.page || 1;
          this.currentTeamId = teamId;
        }
        return res;
      } catch (error) {
        console.error('获取队伍任务失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取任务详情
    async fetchTaskDetail(taskId: number) {
      this.loading = true;
      try {
        const res = await taskApi.getTaskDetail(taskId);
        if (res.code === 200) {
          this.currentTask = res.data;
        }
        return res;
      } catch (error) {
        console.error('获取任务详情失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 创建任务
    async createTask(data: any) {
      try {
        const res = await taskApi.createTask(data);
        if (res.code === 200) {
          // 创建成功后刷新列表
          await this.fetchTaskList({ teamId: this.currentTeamId });
        }
        return res;
      } catch (error) {
        console.error('创建任务失败:', error);
        throw error;
      }
    },

    // 更新任务
    async updateTask(data: any) {
      try {
        const res = await taskApi.updateTask(data);
        if (res.code === 200) {
          // 更新成功后刷新详情和列表
          if (this.currentTask && this.currentTask.id === data.id) {
            this.currentTask = { ...this.currentTask, ...data };
          }
          await this.fetchTaskList({ teamId: this.currentTeamId });
        }
        return res;
      } catch (error) {
        console.error('更新任务失败:', error);
        throw error;
      }
    },

    // 删除任务
    async deleteTask(taskId: number) {
      try {
        const res = await taskApi.deleteTask(taskId);
        if (res.code === 200) {
          // 删除成功后刷新列表
          await this.fetchTaskList({ teamId: this.currentTeamId });
          // 如果删除的是当前任务，清空当前任务
          if (this.currentTask && this.currentTask.id === taskId) {
            this.currentTask = null;
          }
        }
        return res;
      } catch (error) {
        console.error('删除任务失败:', error);
        throw error;
      }
    },

    // 更新任务状态
    async updateTaskStatus(taskId: number, status: number) {
      try {
        const res = await taskApi.updateTaskStatus(taskId, status);
        if (res.code === 200) {
          // 更新成功后刷新详情和列表
          if (this.currentTask && this.currentTask.id === taskId) {
            this.currentTask.status = status;
          }
          const taskIndex = this.taskList.findIndex(t => t.id === taskId);
          if (taskIndex > -1) {
            this.taskList[taskIndex].status = status;
          }
        }
        return res;
      } catch (error) {
        console.error('更新任务状态失败:', error);
        throw error;
      }
    },

    // 更新任务进度
    async updateTaskProgress(taskId: number, progress: number) {
      try {
        const res = await taskApi.updateTaskProgress(taskId, progress);
        if (res.code === 200) {
          // 更新成功后刷新详情和列表
          if (this.currentTask && this.currentTask.id === taskId) {
            this.currentTask.progress = progress;
          }
          const taskIndex = this.taskList.findIndex(t => t.id === taskId);
          if (taskIndex > -1) {
            this.taskList[taskIndex].progress = progress;
          }
        }
        return res;
      } catch (error) {
        console.error('更新任务进度失败:', error);
        throw error;
      }
    },

    // 获取任务评论
    async fetchTaskComments(taskId: number) {
      try {
        const res = await taskApi.getTaskComments(taskId);
        if (res.code === 200) {
          this.taskComments = res.data || [];
        }
        return res;
      } catch (error) {
        console.error('获取任务评论失败:', error);
        throw error;
      }
    },

    // 添加任务评论
    async addTaskComment(data: any) {
      try {
        const res = await taskApi.addTaskComment(data);
        if (res.code === 200) {
          // 添加成功后刷新评论列表
          await this.fetchTaskComments(data.task_id);
        }
        return res;
      } catch (error) {
        console.error('添加任务评论失败:', error);
        throw error;
      }
    },

    // 删除任务评论
    async deleteTaskComment(commentId: number) {
      try {
        const res = await taskApi.deleteTaskComment(commentId);
        if (res.code === 200) {
          // 删除成功后过滤掉该评论
          this.taskComments = this.taskComments.filter(c => c.id !== commentId);
        }
        return res;
      } catch (error) {
        console.error('删除任务评论失败:', error);
        throw error;
      }
    },
  },
});